package com.devunion.salon.dataload;

import org.springframework.orm.jpa.JpaTemplate;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityManager;
import java.util.List;

/**
 * @author spetrakovsky
 */
public class Dataloader implements ApplicationContextAware, InitializingBean {

    private static final Log log = LogFactory.getLog(Dataloader.class);

    private ApplicationContext applicationContext;

    private EntityManagerFactory entityManagerFactory;

    private List<EntityLoader> entityLoaders;

    public void afterPropertiesSet() throws Exception {

        if (entityLoaders != null) {
            EntityManager entityManager = entityManagerFactory.createEntityManager();
            for (final EntityLoader loader : entityLoaders) {
                try {
                    entityManager.getTransaction().begin();
                    loader.loadEntityes(applicationContext, entityManager);
                    log.info(loader.getClass() + " completed successfully");
                    entityManager.getTransaction().commit();
                } catch (Exception e) {
                    log.error(loader.getClass() + " error", e);
                    entityManager.getTransaction().rollback();
                }
            }
        }

    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public EntityManagerFactory getEntityManagerFactory() {
        return entityManagerFactory;
    }

    public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
        this.entityManagerFactory = entityManagerFactory;
    }

    public List<EntityLoader> getEntityLoaders() {
        return entityLoaders;
    }

    public void setEntityLoaders(List<EntityLoader> entityLoaders) {
        this.entityLoaders = entityLoaders;
    }
}
